from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.article.models import Channel, Article
from apps.article.serializers import ChannelsListSerializer, ArticleSerializer, ArticleSerializerList, \
    ArticleSerializerDetail, ArticleSerializerCreate, ArticleCommentSerializer
from apps.activity.views import PageNum
from rest_framework.viewsets import ModelViewSet,ReadOnlyModelViewSet
from rest_framework.decorators import action
from rest_framework.views import status


# 频道列表视图
from apps.question.models import Label


class ChannelsListView(ListAPIView):
    queryset = Channel.objects.all()
    serializer_class = ChannelsListSerializer
    pagination_class = PageNum

#  1 文章视图
class ArticleViewSet(ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    pagination_class = PageNum

    # 2 文章列表  Path： /article/{id}/channel/
    @action(methods=['get'], detail=True, url_path="channel")
    def get_article_by_channel(self,request,pk):
        if pk == "-1":
            articles= self.get_queryset()
        else:
            channel = Channel.objects.get(id=pk)
            articles = self.get_queryset().filter(channel=channel)
        page = self.paginate_queryset(articles)
        if page is not None:
            res = ArticleSerializerList(page,many=True)
            return self.get_paginated_response(res.data)
        else:
            res = ArticleSerializerList(instance=articles,many=True)
            return Response(res.data)

    # 3 收藏和取消收藏文章   /article/{id}/collect/
    @action(methods=['put'], detail=True, url_path="collect")
    def collect(self,request,pk):
        pk = int(pk)
        # 根据id获取到对应的文章
        article = Article.objects.get(id=pk)
        # 判断有数据则是要取消收藏该文章，没数据则收藏文章
        if request.user.collected_articles.filter(id=pk):
            request.user.collected_articles.remove(article)
            return Response({'success':True,'message':'取消收藏成功'})
        else:
            request.user.collected_articles.add(article)
            return Response({'success':True,'message':'收藏成功'})

    # 4 文章详情  /article/{id}
    def retrieve(self,request,*args,**kwargs):
        id = int(self.kwargs['pk'])
        article = Article.objects.get(id=id)
        serializer = ArticleSerializerDetail(article)
        return Response(serializer.data)

    # 5 发布文章  /article/
    def create(self, request, *args, **kwargs):
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            request_params = request.data
            request_params['user'] = user.id
            serializer = ArticleSerializerCreate(data=request_params)
            serializer.request = request
            serializer.is_valid(raise_exception=True)
            article = serializer.save()
            return Response({'success':True,'message':'发布成功','articleid':article.id})
        else:
            return Response({'success':False,'message':'未登录',status:400})

    # 6 评论文章
    @action(methods=['post'], detail=True, url_path='publish_comment')
    def publish_comment(self,request,pk):
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            pk = int(pk)
            data = request.data
            article = Article.objects.get(id=pk)
            data['article'] = pk
            data['user'] = user.id
            serializer = ArticleCommentSerializer(data=data)
            serializer.is_valid()
            serializer.save()
            return Response({'success': True, 'message': '评论成功'})
        else:
            return Response({'success': False, 'message': '未登录', status: 400})

# 7 根据关键字搜索
class SearchView(ReadOnlyModelViewSet):
    serializer_class = ArticleSerializer
    pagination_class = PageNum
    def get_queryset(self):
        # 获取搜索内容
        text = self.request.query_params.get('text')
        #　查询内容
        atr = Article.objects.filter(title__contains=text)
        return atr

# 文章等上传图片
# class ImageUploadView(APIView):
#     def post(self,request):
#         data = request.data
#         img = data.get('img')
#         # 图片上传到fdfs，并返回url和图片路径信息
#         baseurl, file_id = upload(img.read())
#         # 重定向的连接
#         imgurl = baseurl + file_id
#         # 301 重定向
#         return Response({'imgurl': imgurl})